//
//  USAddOurListSubListController.m
//  us
//
//  Created by karry on 2025/5/7.
//

#import "USAddOurListSubListController.h"
#import <CHTCollectionViewWaterfallLayout/CHTCollectionViewWaterfallLayout.h>
#import "USAddOurListSubListHeader.h"
#import "USListModel.h"
#import "USOurListSubCell.h"
#import "USAddOurListDetailVC.h"
#import "DTAlertTextFieldView.h"
#import "USOurListDoneView.h"
@interface USAddOurListSubListController () <UICollectionViewDataSource,UICollectionViewDelegate, CHTCollectionViewDelegateWaterfallLayout>

@property (nonatomic,strong) UIBarButtonItem *addItem;

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray<USListItemModel *> *list;

@property (nonatomic,strong) USAddOurListSubListHeader *header;

@property (nonatomic,strong) USOurListDoneView *doneView;

@end

@implementation USAddOurListSubListController


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.prefersLargeTitles = NO;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    if (self.listModel) {
        [self setupView];

        [self challengeTaskList];
    }else if (self.sweetChallengeId.length > 0){
        [self getsweetChallengeWithID:self.sweetChallengeId success:^{
            
            [self setupView];

            [self challengeTaskList];
        }];
    }

}


- (void)setupView{
    self.addItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_add"] style:UIBarButtonItemStylePlain target:self action:@selector(addAction:)];
    self.navigationItem.rightBarButtonItem = self.addItem;
    
    //这个颜色从模型对象里取
    UIColor *color = [UIColor jk_colorWithHexString:self.listModel.color];
    
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = CGRectMake(0, 0, self.view.jk_width, self.view.frame.size.height * 0.5); // 渐变区域大小
    gradient.colors = @[(__bridge id)color.CGColor,
                        (__bridge id)UIColor.mi_2_color.CGColor]; // 红 -> 黄
    
    gradient.startPoint = CGPointMake(0.5, 0.0); // 顶部中心
    gradient.endPoint = CGPointMake(0.5, 1.0);   // 底部中心
    
    [self.view.layer insertSublayer:gradient atIndex:0];
    
    self.header = [USAddOurListSubListHeader jk_loadInstanceFromNib];
    [self.view addSubview:self.header];
    [self.header mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
    }];
    self.header.color = color;
    self.header.titleLab.text = self.listModel.challengeTitle;
    self.header.progressLab.text = [NSString stringWithFormat:@"%li/%li",self.listModel.completedTaskCount,self.listModel.taskCount];
    if (self.listModel.taskCount == 0) {
        [self.header.progressView setProgress:0];
    }else{
        [self.header.progressView setProgress:self.listModel.completedTaskCount * 1.0/self.listModel.taskCount*1.0];
    }

    // 创建布局
    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
    layout.columnCount = 2;
    layout.minimumColumnSpacing = 12;
    layout.minimumInteritemSpacing = 12;
    layout.sectionInset = UIEdgeInsetsMake(10, 16, 10, 16);

    // 创建 CollectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = UIColor.clearColor;

    [self.collectionView registerClass:[USOurListSubCell class] forCellWithReuseIdentifier:@"USOurListSubCell"];
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight);
        make.top.equalTo(self.header.mas_bottom).offset(0);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
    }];
    
    [self.view addSubview:self.doneView];
    CGFloat stickerViewH = 460 + self.view.window.safeAreaInsets.bottom;
    [self.doneView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight);
        make.bottom.mas_offset(stickerViewH);
        make.height.mas_equalTo(stickerViewH);
    }];
}

- (USOurListDoneView *)doneView {
    if (_doneView == nil) {
        _doneView = [USOurListDoneView jk_loadInstanceFromNib];
        [self.view addSubview:_doneView];
        _doneView.hidden = YES;
        @weakify(self)
        _doneView.listCancelBlock = ^{
            @strongify(self)
            self.doneView.itemModel.hasComplete = NO;
            self.doneView.itemModel.completionStatus = 0;
            self.doneView.itemModel.taskPicUrl = @"";
            [self requestDoneWithModel:self.doneView.itemModel];

        };
        _doneView.listDoneBlock = ^{
         @strongify(self)
            if (self.doneView.itemModel.deletePic) {
                self.doneView.itemModel.taskPicUrl = @"";
            }
            if (self.doneView.itemModel.completionStatus == 1) {
                self.doneView.itemModel.hasComplete = YES;//本身已经是完成
            }
            self.doneView.itemModel.completionStatus = 1;
            [self requestDoneWithModel:self.doneView.itemModel];
        };
        
        _doneView.listDeleteBlock = ^{
          @strongify(self)
            [self deleteAction:self.doneView.itemModel];
        };
     }
    return _doneView;
}
- (NSMutableArray <USListItemModel *>*)list {
    if (_list == nil) {
        _list = [NSMutableArray array];
    }
    return _list;
}



#pragma mark - net
- (void)getsweetChallengeWithID:(NSString *)sweetChallengeId success:(void(^)(void))success {
    [[EMNetWork shareManager] em_post:API_DailyChallengeView
                               params:@{@"sweetChallengeId":sweetChallengeId?:@""}
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            return;
        }
        USListModel *model = [USListModel mj_objectWithKeyValues:api.data[@"sweetChallenge"]];
        self.listModel = model;
        
        success();
    } fail:^{
        
        
    }];
}
- (void)challengeTaskList {
 
    [[EMNetWork shareManager] em_post:API_DailyChallengeTaskList
                               params:@{@"sweetChallengeId":self.listModel.sweetChallengeId?:@""}
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            [self loadingFailed];
            return;
        }
        NSArray *list = [USListItemModel mj_objectArrayWithKeyValuesArray:api.data[@"challengeTaskList"]];
        
        [self.list removeAllObjects];
        
        [self.list addObjectsFromArray:list];
        if (list.count == 0) {
            self.dataState = EmptyDataStateNoData;
        }
        
        [self.collectionView reloadData];
        [self.collectionView reloadEmptyDataSet];
        
        
    } fail:^{
        
        
    }];
    
}
///新建
- (void)saveAction:(NSString *)title{
    [USFeedbackTool impactSoft];
    
    if (title.length == 0) {
        return;
    }
  
    [self startUpload];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"taskTitle"] = title;
    params[@"sweetChallengeId"] = self.listModel.sweetChallengeId?:@"";
    
    [[EMNetWork shareManager] em_post:API_DailyChallengeTaskAdd
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {

        [self endUpLoad];
        if (!api.success) {
            return;
        }
        
        USListItemModel *model = [USListItemModel mj_objectWithKeyValues:api.data[@"ChallengeTask"]];
        
        self.listModel.taskCount ++;
        self.header.progressLab.text = [NSString stringWithFormat:@"%li/%li",self.listModel.completedTaskCount,self.listModel.taskCount];
        if (self.listModel.taskCount == 0) {
            [self.header.progressView setProgress:0];
        }else{
            [self.header.progressView setProgress:self.listModel.completedTaskCount * 1.0/self.listModel.taskCount*1.0];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView performBatchUpdates:^{
                [self.list addObject:model];
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.list.count - 1 inSection:0];
                [self.collectionView insertItemsAtIndexPaths:@[indexPath]];
            } completion:nil];

        });
    } fail:^{
        
        [self endUpLoad];

    }];
    
    
}
///删除
- (void)deleteAction:(USListItemModel *)itemModel {
    MOAlertBaseView *alert = [[MOAlertBaseView alloc]initWithTitle:@"确定删除此小事吗" detailTitle:@"此操作不可撤销哦，请谨慎操作" contentView:nil leftButtonImageName:nil rightButtonImageName:nil autoDissmiss:YES tapDissmiss:YES];
    alert.titleLabel.textColor = UIColor.us_redColor;
    @weakify(self)
    alert.didClickIndexBlock = ^(NSInteger index) {
        @strongify(self)
        if (index == 1) {
            [self deleteList:itemModel];
        }
    };
    
    [alert show];
}

- (void)deleteList:(USListItemModel *)itemModel {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"challengeTaskId"] = itemModel.challengeTaskId;
    
    [[EMNetWork shareManager] em_post:API_DailyChallengeTaskDelete
                               params:params
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        
        if (!api.success) {
            return;
        }
        [USFeedbackTool notifySuccess];

        NSLog(@"itemModel.challengeTaskId == %@",itemModel.challengeTaskId);

        NSIndexPath *indexPath;
        for (int i= 0; i<self.list.count; i++) {
            USListItemModel *model = self.list[i];
            NSLog(@"model.challengeTaskId == %@",model.challengeTaskId);
            if ([itemModel.challengeTaskId isEqualToString: model.challengeTaskId]) {
                indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                break;
            }
        }
        if (indexPath) {
            
            self.listModel.taskCount --;
            if (itemModel.completionStatus == 1) {
                self.listModel.completedTaskCount--;
            }
            self.header.progressLab.text = [NSString stringWithFormat:@"%li/%li",self.listModel.completedTaskCount,self.listModel.taskCount];
            if (self.listModel.taskCount == 0) {
                [self.header.progressView setProgress:0];
            }else{
                [self.header.progressView setProgress:self.listModel.completedTaskCount * 1.0/self.listModel.taskCount*1.0];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView performBatchUpdates:^{
                    [self.list removeObjectAtIndex:indexPath.row];
                    [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
                } completion:nil];
                
                if (self.list.count == 0) {
                    self.dataState = EmptyDataStateNoData;
                    [self.collectionView reloadData];
                    [self.collectionView reloadEmptyDataSet];
                }
                
            });
        }
      
    } fail:^{
        
        
    }];
}

/// 打卡
- (void)requestDoneWithModel:(USListItemModel *)itemModel {
    [USFeedbackTool impactSoft];
 
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"completionStatus"] = @(itemModel.completionStatus);
    params[@"taskTitle"] =  itemModel.taskTitle;
    params[@"completionTime"] = @(itemModel.completionTime);
    params[@"taskPicUrl"] = itemModel.taskPicUrl;


    params[@"sweetChallengeId"] = itemModel.sweetChallengeId?:@"";
    params[@"challengeTaskId"] = itemModel.challengeTaskId;

    NSLog(@"params = %@",params);
    [[EMNetWork shareManager] em_post:API_DailyChallengeTaskEdit
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {
 
        if (!api.success) {
            return;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (itemModel.completionStatus == 1) {
                if (!itemModel.hasComplete) {
                    self.listModel.completedTaskCount++;
                }
                
                [self remindActionWithModel:itemModel];
            }else {
                self.listModel.completedTaskCount--;
            }
            self.header.progressLab.text = [NSString stringWithFormat:@"%li/%li",self.listModel.completedTaskCount,self.listModel.taskCount];
            if (self.listModel.taskCount == 0) {
                [self.header.progressView setProgress:0 animated:YES];
            }else{
                [self.header.progressView setProgress:self.listModel.completedTaskCount * 1.0/self.listModel.taskCount*1.0 animated:YES];
            }
            [self.collectionView reloadData];
        });
    } fail:^{
         
    }];
    
    
}


#pragma mark - 提醒Ta
- (void)remindActionWithModel:(USListItemModel *)model {

    NSString *action_title = [NSString stringWithFormat:@"%@打卡了一件小事",USUser.user.nickname];
    NSDictionary *ext = @{@"action_id":model.sweetChallengeId,
                          @"action_title":action_title,
                          @"action_content":model.taskTitle};
    
    [USIMCmdCustomManager imSendCmdWithAction:USIMCmdAction_ListDone andExt:ext];

    [USIMCmdCustomManager imSendCustomWithEvent:USIMCmdAction_ListDone andCustomExt:ext];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@(USNoticeType_List) forKey:@"type"];
    [param setValue:model.sweetChallengeId forKey:@"pkId"];
    [param setValue:@"打卡了一件小事" forKey:@"content"];
    [param setValue:USUser.user.relUser.userId forKey:@"userId"];
    [param setValue:@(1) forKey:@"shareSpaceFlag"];

    [[EMNetWork shareManager] em_post:NoticeAdd
                               params:param
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
    } fail:^{
        
        
    }];
}
#pragma mark - action

- (void)startUpload{
    [self.indicator startAnimating];
    UIBarButtonItem *loadingItem = [[UIBarButtonItem alloc] initWithCustomView:self.indicator];
    self.navigationItem.rightBarButtonItem = loadingItem;
    self.view.userInteractionEnabled = NO; // 禁用整个页面操作

    
}
- (void)endUpLoad{
    self.navigationItem.rightBarButtonItem = self.addItem;
    [self.indicator stopAnimating];
    self.view.userInteractionEnabled = YES;
}
- (void)addAction:(id)sender{
    [USFeedbackTool impactSoft];
    
    DTAlertTextFieldView *tfView = [DTAlertTextFieldView alertContentView];
    tfView.textField.placeholder = @"写一件小事吧";
    tfView.textField.jk_maxLength = 25;
    
    MOAlertBaseView *alert = [[MOAlertBaseView alloc]initWithTitle:@"新建打卡小事" detailTitle:nil contentView:tfView leftButtonImageName:nil rightButtonImageName:nil autoDissmiss:NO tapDissmiss:YES];
    
    @weakify(self)
    @weakify(alert)
    alert.didClickIndexBlock = ^(NSInteger index) {
        @strongify(self)
        @strongify(alert)
        if (index == 1) {

            [self saveAction:tfView.textField.text];
            [alert dismss];
        }else{
            [alert dismss];
        }
        
    };
    [alert show];
}

- (void)litDoneActionWithIndexPath:(NSIndexPath *)indexPath {
    USListItemModel *model = self.list[indexPath.row];

    self.doneView.itemModel = model;
    [self.doneView showLitPickerWithAllowTapDismiss:YES];
    
    
}
#pragma mark - UICollectionViewDataSource

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
//    USAddOurListDetailVC *vc = [USAddOurListDetailVC new];
//    vc.itemModel = self.list[indexPath.row];
//    [self.navigationController pushViewController:vc animated:YES];
    
    [self litDoneActionWithIndexPath:indexPath];

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.list.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    USOurListSubCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"USOurListSubCell" forIndexPath:indexPath];

    USListItemModel *model = self.list[indexPath.row];
    cell.model = model;
    return cell;
}

#pragma mark - CHTCollectionViewDelegateWaterfallLayout
 
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
   
    CGFloat width = (self.view.jk_width - 32 - 12) / 2; // 2列间距计算
    CGFloat height = 50;
    USListItemModel *model = self.list[indexPath.item];
    if (model.taskPicUrl.length > 0) {
        height =  50 + (self.view.jk_width - 32 - 10)/2;
    }
    return CGSizeMake(width, height);

}
 
 
@end
